package com.kili.picture.config;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.kili.picture.context.exception.DataException;
import com.kili.picture.tools.LocalCacheHolder;
import com.kili.picture.service.PictureConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author Jar
 * @Date 2019/4/1
 */
@Component
@Order(2)
public class StartupRunner implements CommandLineRunner {

    private static final Logger logger = LoggerFactory.getLogger(StartupRunner.class);

    @Autowired
    private PictureConfigService pictureConfigService;

    @Override
    public void run(String... args) {
        loadPictureConfig();
    }

    private void loadPictureConfig() {
        LoadingCache<String, Object> caches = CacheBuilder.newBuilder().maximumSize(1000)
                .expireAfterAccess(15, TimeUnit.MINUTES).build(new CacheLoader<String, Object>() {

                    @Override
                    public Object load(String key) {
                        String prefix = pictureConfigService.getPrefixByModule(key);

                        if (StringUtils.isEmpty(prefix)) {
                            logger.error("get module {} prefix error", key);
                            throw new DataException("get module prefix error");
                        }

                        return prefix;
                    }

                });

        LocalCacheHolder.setCache(PictureConfigService.CACHE_KEY, caches);
    }

}
